package com.example.fw;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.GroupData;
import com.example.utils.SortedListOf;

public class GroupHelper extends WebDriverHelperBase {


			
	public GroupHelper modifyGroup(int index, GroupData group) {
		manager.navigateTo().groupsPage();
		initGroupModification(index);
		fillGroupForm(group);
		submitGroupModification();
		returnToGroupsPage();
		return this;
	}
	
	public GroupHelper createGroup(GroupData group) {
		manager.navigateTo().groupsPage();
		initGroupCreation();
		fillGroupForm(group);
		submitGroupCreation();
		returnToGroupsPage();
		return this;
	}
	
	public GroupHelper deleteGroup(int index) {
		selectGroupByIndex(index);	
		submitGroupDeletion();
		returnToGroupsPage();
		return this;
		}
// ---------------------------------------------------------------------------------



	public SortedListOf<GroupData> getUiGroups() {
		SortedListOf<GroupData> groups = new SortedListOf<GroupData>();
		manager.navigateTo().groupsPage();
		System.out.println("On groups page");
		List<WebElement> checkboxes = driver.findElements(By.name("selected[]"));
		//System.out.println("all values found");
		for (WebElement checkbox : checkboxes) {
		String title = checkbox.getAttribute("title");
		String name = title.substring("Select (".length(), title.length()-")".length());
		groups.add(new GroupData().withName(name));
		//System.out.println("name found " + name);
			}
		return groups;
		}
	
	public void submitGroupDeletion() {
	click(By.name("delete"));
	}
	
	public GroupHelper(ApplicationManager manager) {
	super(manager);
	}

	public GroupHelper initGroupCreation() {
	click (By.name("new"));
	return this;
	}

	public GroupHelper returnToGroupsPage() {
	click (By.linkText("group page"));
	return this;
	}

	
	public GroupHelper submitGroupCreation() {
	click(By.name("submit"));
	return this;
	}
	
	public GroupHelper fillGroupForm(GroupData group) {
	type(By.name("group_name"), group.getName());
	type(By.name("group_header"), group.getHeader());
	type(By.name("group_footer"), group.getFooter());
	return this;
	}

	private void selectGroupByIndex(int index) {
	click(By.xpath("//input[@name='selected[]']["+(index+1)+"]"));
	}

	public GroupHelper initGroupModification(int index) {
	selectGroupByIndex(index);		
	click(By.name("edit"));
	return this;
	}

	public GroupHelper submitGroupModification() {
	click(By.name("update"));
	return this;
	}

}